#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <assert.h>
#include <unistd.h>
#include <string.h>
#include <stdio.h>
#include <iostream>

int caculate(int cnt,int *buffer,char op)
{
    int result = buffer[0];
    if(op == '+')
    {
        for(int i=1;i<cnt;i++)
        {
            result += buffer[i];
        }
    }
    else if(op == '-')
    {
        for(int i=1;i<cnt;i++)
        {
            result -= buffer[i];
        }
    }
    else if(op == '*')
    {
        for(int i=1;i<cnt;i++)
        {
            result *= buffer[i];
        }
    }
    else if(op == '/')
    {
        for(int i=1;i<cnt;i++)
        {
            result /= buffer[i];
        }
    }
    return result;
}

int main()
{
    int listenfd = socket(AF_INET,SOCK_STREAM,0);
    
    struct sockaddr_in server;
    server.sin_family = AF_INET;
    server.sin_port = htons(9090);
    server.sin_addr.s_addr = INADDR_ANY;
    int n = bind(listenfd,(const sockaddr *)&server,sizeof(server));
    assert(n != -1);

    n = listen(listenfd,5);
    assert(n != -1);
    sleep(10);
    struct sockaddr_in client;
    socklen_t len = sizeof(client);

    for(int i=0;i<5;i++)
    {
        int sockfd = accept(listenfd,(sockaddr *)&client,&len);
        assert(sockfd != -1);

        int opt_num = 0;
        recv(sockfd,&opt_num,1,0);// 读取数字的个数
        std::cout << "获取到数字的个数: " << opt_num << std::endl;

        int recv_len = 0;
        char buffer[1024] = {0};
        while(recv_len < opt_num * 4 + 1)
        {
            int n = recv(sockfd,&buffer[recv_len],sizeof(buffer)-1,0);// 读取操作数和操作符
            recv_len += n;
            std::cout << "n = " << n << std::endl;
        }
        int* arr = (int*)(buffer);
        for (int i = 0; i < opt_num; i++)
        {
            std::cout << arr[i];
        }
        std::cout << "操作符: " << buffer[recv_len-1] << std::endl;
        int result = caculate(opt_num,(int*)buffer,buffer[recv_len-1]);
        send(sockfd,(char *)&result,sizeof(result),0);
        close(sockfd);
    }

    close(listenfd);
    return 0;
}